//
//  IPMysql.m
//  iphone_test
//
//  Created by whlsxl on 10-5-9.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "IPMysql.h"
#import	"mysql.h"

#define IP_MYSQL_SHOW_LOG

#pragma mark static variables
MYSQL *mysql;
int is_use;

@implementation IPMysql

#pragma mark method's method
- (void)showLog{
	error_msg = [NSString stringWithCString:mysql_error(mysql) encoding:NSASCIIStringEncoding ];
#ifdef IP_MYSQL_SHOW_LOG
	NSLog(@"%@",error_msg);
#endif
}

-(id) init{
	[super init];
	
	
	host = "192.168.0.150";
	user = "root";
	passwd = nil;
	db = "123";
	port = 3306;
	unix_socket = nil;
	clientflag = 0;
	
	srs = nil;
	
	return self;
}

- (unsigned int)connect{
	mysql = mysql_init(nil);
	if(!(mysql_real_connect(mysql, host, user, passwd, db, port, unix_socket, clientflag))){
		[self showLog];
		return mysql_errno(mysql);
	}
	if (mysql_set_character_set(mysql, "utf8")) {
		[self showLog];
		return mysql_errno(mysql);
	}
	return 0;
}

- (unsigned int)query:(NSString *)statement{
	if (mysql == nil){
		int error_no = [self connect];
		if (error_no){
			return error_no;
		}
	}
	int cycle;
	while (is_use) {
//		[NSDate  
	}
	if (mysql_real_query(mysql, [statement UTF8String], strlen([statement UTF8String]))) {
		[self showLog];
		return mysql_errno(mysql);
	}
	if (mysql_field_count(mysql)) {
		if (srs != nil) {
			[srs release];
			srs = nil;
		}
		srs = [[SqlResultSet alloc] init];
		MYSQL_RES *res = mysql_store_result(mysql);
		if (res == 0) {	
			[self showLog];
			return mysql_errno(mysql);
		}
		int count_field;
		count_field = mysql_num_fields(res);
		MYSQL_FIELD *fields = mysql_fetch_fields(res);
		for (cycle = 0; cycle < count_field; cycle++) {
			[srs setNameAtt:[NSString stringWithCString:fields[cycle].name encoding: NSUTF8StringEncoding]];
		}
		int count_row = mysql_num_rows(res);
		MYSQL_ROW row;
		for (cycle = 0; cycle < count_row; cycle++) {
			row = mysql_fetch_row(res);
			for (int cycle_2 = 0; cycle_2 < count_field; cycle_2++) {
				if (row[cycle_2] == 0) {
					[srs addItem:[NSString string]];
				}
				else{
					[srs addItem:[NSString stringWithCString:row[cycle_2] encoding:NSUTF8StringEncoding]];
				}
			}
		}
		mysql_free_result(res);
		return 0;
	}
	return 0;
}

- (SqlResultSet *)getResult{
	if(srs)
		return srs;
	return nil;
}
- (void)release{
	if (srs) {
		[srs release];
	}
	mysql_close(mysql);
	mysql = nil;
	[super release];
}

- (NSString *)getErrorMsg{
	return error_msg;
}

@end
